#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File    :   framingham.py
@Time    :   2020/11/26
@Author  :   wenke wang
@Version :   1.0
@Desc    :   Framingham风险评估模型
'''

# here put the import lib
import sys, os, json
from decimal import Decimal
from framingham_eval_param import FraminghamEvalParam

def get_default_settings():
    """
    获取默认的评分配置
    """
    default_setting = None

    setting_path = os.path.join(sys.path[0], "framingham_score_setting.json")
    with open(setting_path, "r", encoding="utf-8") as fp:
        default_setting = json.load(fp)
    
    return default_setting


def evaluate(param, score_settings = None):
    """
    Framingham10年风险评估模型
    """
    
    if not score_settings:
        score_settings = get_default_settings()
    
    score_key = "%s_score" % param.gender.lower()

    total_score = 0
    
    # 年龄得分
    total_score = total_score + [s[score_key] for s in score_settings["age"] if s["low"] <= param.age and s["high"] >= param.age][0]

    # TC得分
    total_score = total_score + [a[score_key] for s in score_settings["tc"] if Decimal(str(s["low"])) <= param.tc and Decimal(str(s["high"])) >= param.tc for a in s["age"] if a["low"] <= param.age and a["high"] >= param.age][0]

    # HDL-C得分
    total_score = total_score + [s[score_key] for s in score_settings["hdlc"] if Decimal(str(s["low"])) <= param.hdlc and Decimal(str(s["high"])) >= param.hdlc][0]

    # 吸烟得分
    total_score = total_score + [a[score_key] for s in score_settings["smoking"] if s["val"] == param.smoking for a in s["age"] if a["low"] <= param.age and a["high"] >= param.age][0]

    # 收缩压得分
    treat_key = "treat_%d" % param.treat
    total_score = total_score + [s[treat_key][score_key] for s in score_settings["sbp"] if s["low"] <= param.sbp and s["high"] >= param.sbp][0]

    # 风险值%
    percent_key = "%s_percent" % param.gender.lower()
    score_low = score_settings["risk"][percent_key][0]
    score_high = score_settings["risk"][percent_key][-1]
    if total_score < score_low["score"]:
        return { "score": total_score, "percent": score_low["symbol"]["val"] + "%", "risk10": "low" }
    elif total_score >= score_high["score"]:
        return { "score": total_score, "percent": score_high["symbol"]["val"] + "%", "risk10": "high" }

    f_risk = lambda v: "low" if v < 10 else "middle" if v >= 10 and v <= 20 else "high"
    risk = [(s["symbol"] + str(s["val"]), f_risk(s["val"])) for s in score_settings["risk"][percent_key] if s["score"] == total_score][0]
    return { "score": total_score, "percent": str(risk[0]) + "%", "risk10": risk[1] }

if __name__ == "__main__":
    param = FraminghamEvalParam(57, 'F', 1, 169, 0, 280, 40)
    res = evaluate(param)
    print(res)

